import { axios } from "@/tools/request"

export default {
	state: {
		message: {
			examQuestionDTOList: [],
			title: "",
		},
		current: 0,
	},
	mutations: {
		setMessage(state, data) {
			state.message = data
		},
		setCurrent(state, current) {
			state.current = current
		},
		setAnswer(state, { answer, index }) {
			const list = state.message.examQuestionDTOList
			list[index].choiceAnswer = answer.join(",")
			state.message.examQuestionDTOList = [].concat(list)
		},
	},
	actions: {
		async isHasExam({ commit }, id) {
			const data = await axios.get("/api/study/exam/studyExam/unfinish/" + id)
			return data
		},
		async getExam({ commit }, { id, type, save }) {
			let data

			switch (type) {
				// 获取试卷基本信息, 不创建试卷
				case "new":
					data = await axios.get("/api/study/exam/studyExam/detail/basicInfo/" + id)
					data.examQuestionDTOList = []
					commit("setCurrent", 0)
					commit("setMessage", data)
					return data
				// 获取试卷基本信息, 创建试卷
				case "set":
					data = await axios.get("/api/study/exam/studyExam/detail/" + id)
					commit("setCurrent", 0)
					commit("setMessage", data)
					return data
				case "finish":
					data = await axios.get("/api/study/exam/studyExam/memberExamInfo/" + id)
					commit("setCurrent", 0)
					commit("setMessage", data)
					return data

				case "learn":
					data = await axios.get("/api/study/exam/studyQuestion/list/" + id)
					commit("setCurrent", 0)
					commit("setMessage", {
						examQuestionDTOList: data,
					})
					return {
						examQuestionDTOList: data,
					}

				// 获取之前考试的试卷信息
				default:
					const { examCurrentIndex, examInfo } = await axios.get(
						"/api/study/exam/studyExam/unfinishDetail/" + id
					)

					commit("setCurrent", examCurrentIndex - 1)
					commit("setMessage", examInfo)
					return examInfo
			}
		},
		async saveAnswer({ commit, state, getters }, { index }) {
			const question = getters.questionList[index]
			await axios.post("/api/study/exam/studyExam/saveOneQuestion", {
				id: question.id,
				examId: question.examId,
				choiceAnswer: question.choiceAnswer,
			})

			commit("setAnswer", { answer: question.choiceAnswer.split(","), index })
		},
		async clearExam({}, id) {
			await axios.get("/api/study/exam/studyExam/unfinish/del/" + id)
		},
	},
	getters: {
		questionLength(state) {
			return state.message.examQuestionDTOList
				? state.message.examQuestionDTOList.length
				: +state.message.multipleNum + +state.message.singleNum
		},
		questionList(state) {
			return state.message.examQuestionDTOList
		},
		nowQuestion(state) {
			return state.message.examQuestionDTOList[state.current] || {}
		},
		nowAnswer(_state, getters) {
			return getters.nowQuestion.choiceAnswer ? getters.nowQuestion.choiceAnswer.split(",") : []
		},
		answer(_state, getters) {
			return getters.questionList.map(item => {
				return item.choiceAnswer ? item.choiceAnswer.split(",") : []
			})
		},
	},
	namespaced: true,
}
